import mitt from 'mitt'
import type { App } from 'vue'

interface EventBusWithInstall extends ReturnType<typeof mitt> {
    install: (app: App, options?: EventBusOptions) => void
}

const eventBus: EventBusWithInstall = mitt() as EventBusWithInstall

const defaultOptions = {
    global: true,
    inject: true,
    globalPropertyName: '$eventBus',
    injectName: '$eventBus'
}

interface EventBusOptions {
    global?: boolean
    inject?: boolean
    globalPropertyName?: string
    injectName?: string
}

eventBus.install = function (app: App, options?: EventBusOptions) {
    let opt = {
        ...defaultOptions,
        ...options
    }
    if (opt.global) {
        app.config.globalProperties[opt.globalPropertyName] = eventBus;
    }
    if (opt.inject) {
        app.provide(opt.injectName, eventBus)
    }
    return eventBus
}

export default eventBus
export const bus = eventBus
